<?php
require 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $new_username = $_POST['new_username'];
    $hashed_password = $_POST['hashed_password'];
    $phone = $_POST['phone'];

    // 检查用户名和密码是否为空
    if (empty($new_username) || empty($hashed_password) || empty($phone)) {
        echo "<script>
            alert('用户名,密码和电话号码不能为空');
            window.location.href = 'register.html'; // 注册表单文件名为 register.html
        </script>";
        exit();
    }

    try {
        // 检查用户名是否已存在
        $stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->bind_param("s", $new_username);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $stmt->close();
            throw new Exception("用户名已存在，请选择另一个用户名。");
        }
        $stmt->close();

        // 插入新用户数据
        $stmt = $conn->prepare("INSERT INTO users (username, password, phone) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $new_username, $hashed_password,$phone);
        $stmt->execute();
        $stmt->close();

        echo "<script>
            alert('注册成功，欢迎 " . htmlspecialchars($new_username) . "！');
            window.location.href = 'profile.html';
        </script>";
    } catch (Exception $e) {
        echo "<script>
            alert('注册失败: " . $e->getMessage() . "');
            window.location.href = 'login_form.html'; //
        </script>";
    }
}
?>
